import axios from 'axios'
import { client_id, client_secret, redirect_uri } from '@/assets/giteeConfig'

export const toLogin = () => {
  location.href = `https://gitee.com/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code`
}

const httpOauth = axios.create({
  baseURL: 'https://gitee.com/oauth'
})
httpOauth.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response.status === 401) {
      toLogin()
    }
    return Promise.reject(error)
  }
)

function setGiteeToken(res: any) {
  localStorage.gitee_access_token = res.access_token
  localStorage.gitee_refresh_token = res.refresh_token
}

export const getTokenByCode = (code: string) => {
  return httpOauth
    .post('token', {
      grant_type: 'authorization_code',
      code,
      client_id,
      client_secret,
      redirect_uri
    })
    .then((res) => {
      setGiteeToken(res)
      location.href = redirect_uri
      return res
    })
}

let refreshTokenPromise: Promise<void> | undefined
export const refreshToken = () => {
  if (refreshTokenPromise) {
    return refreshTokenPromise
  }
  refreshTokenPromise = httpOauth
    .post('token', {
      grant_type: 'refresh_token',
      refresh_token: localStorage.gitee_refresh_token
    })
    .then((res) => {
      setGiteeToken(res)
      refreshTokenPromise = void 0
      return
    })
  return refreshTokenPromise
}
